﻿using GPSTrackingWebsiteManager.ClassManager;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace GPSTrackingWebsiteManager.Map.Pages
{
    public partial class ChangePassword : ClassManager.SessionManagerPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (String.IsNullOrEmpty(txtPasswordNow.Text))
            {
                showErrorMessage("Debe digitar la contraseña actual");
                return;
            }

            if (String.IsNullOrEmpty(txtPassword1.Text))
            {
                showErrorMessage("Debe digitar la nueva contraseña");
                return;
            }

            if (String.IsNullOrEmpty(txtPassword2.Text))
            {
                showErrorMessage("Debe digitar la contraseña de seguridad");
                return;
            }

            if (txtPassword1.Text != txtPassword2.Text)
            {
                showErrorMessage("Las dos contraseñas no son iguales");
                return;
            }


            string PasswordNowEncrypt = EncryptaionManager.EncryptionManager.Encrypt(txtPasswordNow.Text, new System.Security.Cryptography.SHA256CryptoServiceProvider());

            SessionManager objSessionManager = (SessionManager)HttpContext.Current.Session["SessionManager"];
            if (objSessionManager.IsUser)
            {
                GPSTrackingDBV2.Entities.Users userEntity = GPSTrackingDBV2.Data.DataRepository.UsersProvider.GetByUsernameCompanyId(objSessionManager.Username, objSessionManager.CompanyID);
                if (userEntity.Password != PasswordNowEncrypt)
                {
                    showErrorMessage("La contraseña actual no es valida");
                    return;
                }

                string Password1 = EncryptaionManager.EncryptionManager.Encrypt(txtPassword1.Text, new System.Security.Cryptography.SHA256CryptoServiceProvider());

                userEntity.Password = Password1;

                GPSTrackingDBV2.Data.DataRepository.UsersProvider.Update(userEntity);
            }
           

            ShowMessage("Contraseña fue cambiada");

        }

        public void showErrorMessage(string msg)
        {
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "objWindowsMessageManager.show_Error", "objWindowsMessageManager.show_Error('" + msg + "','Cambio de contraseña...');", true);
        }

        public void ShowMessage(string msg)
        {
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "objWindowsMessageManager.show_Info", "objWindowsMessageManager.show_Info('" + msg + "','Recuperación de contraseña');", true);
        }
    }
}